#include <QUrl>
#include <QVBoxLayout>

#include "containerwidget.h"
#include "flowlayout.h"
#include "global.h"
#include "dbreader.h"
#include "imageitemproxy.h"

static void clearLayout(QLayout* layout)
{
    QLayoutItem *item;
    while ((item = layout->takeAt(0)))
        delete item;
}

class ContainerWidgetPrivate
{
public:
    int imageCountPerPage = 5;
    ContainerWidget::ImageCategory imageCategory = ContainerWidget::Good;
    int goodImageCounter = 0;
    int newImageCounter = 0;
    QList<ImageData> goodImages;
    QList<ImageData> newImages;

    QVBoxLayout* layout;
};

ContainerWidget::ContainerWidget(QWidget *parent) : QScrollArea(parent)
{
    d_ptr = new ContainerWidgetPrivate;

    d_ptr->goodImages = DbReader::instance()->queryGoodImages();
    d_ptr->newImages = DbReader::instance()->queryNewImages();

    d_ptr->layout = new QVBoxLayout;

    QWidget* widget = new QWidget(this);
    widget->setStyleSheet("background:gray;");
    widget->setLayout(d_ptr->layout);
    setWidgetResizable(true);
    setWidget(widget);
}

ContainerWidget::~ContainerWidget()
{
    delete d_ptr;
}

void ContainerWidget::setImageCategory(ImageCategory ic)
{
    if (d_ptr->imageCategory != ic)
        d_ptr->imageCategory = ic;
}

ContainerWidget::ImageCategory ContainerWidget::imageCategory() const
{
    return d_ptr->imageCategory;
}

void ContainerWidget::setImageCountPerPage(int count)
{
    if (d_ptr->imageCountPerPage != count)
        d_ptr->imageCountPerPage = count;
}

int ContainerWidget::imageCountPerPage()
{
    return d_ptr->imageCountPerPage;
}

static inline void limit(int& num, int max)
{
    if (num > max)
        num = max;
}

void ContainerWidget::next()
{
    int counter = 0;
    if (d_ptr->imageCategory == ContainerWidget::Good) {
        while (counter < d_ptr->imageCountPerPage) {
            if (d_ptr->goodImageCounter < d_ptr->goodImages.size()) {
                const ImageData& id = d_ptr->goodImages.at(d_ptr->goodImageCounter);
                ImageItemProxy* iip = new ImageItemProxy(this);
                iip->setUrl(QUrl(id.url));
                iip->setDescription(id.desc);
                d_ptr->layout->addWidget(iip);
                d_ptr->goodImageCounter++;
            }
            counter++;
        }
    } else {
        while (counter < d_ptr->imageCountPerPage) {
            if (d_ptr->newImageCounter < d_ptr->newImages.size()) {
                const ImageData& id = d_ptr->newImages.at(d_ptr->newImageCounter);
                ImageItemProxy* iip = new ImageItemProxy(this);
                iip->setUrl(QUrl(id.url));
                iip->setDescription(id.desc);
                d_ptr->layout->addWidget(iip);
                d_ptr->newImageCounter++;
            }
            counter++;
        }
    }
}

void ContainerWidget::clear()
{
//    d_ptr->layout->clear();
    clearLayout(d_ptr->layout);
    d_ptr->goodImageCounter = 0;
    d_ptr->newImageCounter = 0;
}

